<?php
declare (strict_types=1);

namespace app\course\logic\base;

use app\common\exception\LogicException;
use app\course\logic\classes\ClassesLink;
use app\course\model\base\CourseStudent as CourseStudentModel;
use app\user\logic\user\VipUser;

/**
 * 课程学员
 * @method whereCourseId(int $courseId)
 */
class CourseStudent extends CourseStudentModel
{

    /**
     * 课程是否购买
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-21
     */
    public function isBuy($course_id, $mid = 0): int
    {
        $mid = $mid ?: request()->mid;
        // 关联的班级
        $ids = app(ClassesLink::class)->where('course_id', $course_id)->column('classes_id');
        array_unshift($ids, $course_id);

        $has = $this->scope('mid', $mid)->where('course_id', 'IN', $ids)->whereRaw('expire_time >' . time() . ' OR expire_time is null')->count();

        return $has ? 1 : 0;
    }

    /**
     * 课程有效期
     */
    public function getTermRest($course_id)
    {
        // 关联的班级
        $ids = app(ClassesLink::class)->where('course_id', $course_id)->column('classes_id');
        array_unshift($ids, $course_id);

        $has = $this->scope('mid')->where('course_id', 'IN', $ids)->whereRaw('expire_time >' . time() . ' OR expire_time is null')->select();

        if ($has->isEmpty()) return 0;

        $time_arr = array_column($has->toArray(), 'expire_time');
        if (in_array(null, $time_arr)) return -1;

        sort($time_arr);
        return max(0, end($time_arr) - time());
    }

    public function getCourseStudents($course_id)
    {
        return $this->field('user_id,from')->where('course_id', $course_id)->with(['user.avatarUrl'])->select()
            ->bindAttr(
                'user',
                ['nick_name', 'avatar_url']
            )->hidden(['user'])->append(['from_text']);
    }

    public function removeStudent($course_id, $user_id)
    {
        $data = $this->where('course_id', $course_id)->where('user_id', $user_id)->findOrEmpty();

        if (!$data->isEmpty()) {
            if ($data->delete()) {
                return true;
            } else {
                throw new LogicException('移除失败');
            }
        }
    }

    /**
     * 免费课程加入学习
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-18
     */
    public function joinCourseStudent($param)
    {
        // 验证数据
        $this->getValidate()->scene('add')->failException()->check($param);

        // 参数
        $course_id = $param['course_id'];
        $mid       = static::$mid;

        // 课程是否免费
        $course = app(Course::class)->where('id', $course_id)->field('price,vip_price,term_time,course_type,limit_buy_count')->findOrEmpty();

        if ($course->user_price != 0) {
            throw new LogicException('课程非免费，不能加入');
        }

        $from   = 4;
        $expire = null;
        $term   = $course->term_time;
        $term && $expire = strlen($term . '') > 4 ? $term : time() + $term * 86400;

        if ($course->price) {
            $is_vip = app(VipUser::class)->isVip();
            if ($is_vip) {
                $from = 5;
            } else {
                throw new LogicException('课程非免费，不能加入');
            }
        }
        // 小班课人数限制
        if ($course->course_type == 2 && $course->limit_buy_count) {
            $count = $this->where('course_id', $course_id)->count();
            if ($count >= $course->limit_buy_count) throw new LogicException('课程已限制购买');
        }

        $have = $this->scope('mid')->where('course_id', $course_id)->findOrEmpty();
        if ($have->isEmpty()) {
            $data = [
                'user_id'     => $mid,
                'course_id'   => $course_id,
                'from'        => $from,
                'expire_time' => $expire,
            ];

            $res = $this::create($data);

            if ($res->isEmpty()) {
                throw new LogicException('加入失败');
            }
        } else {
            $have->expire_time = $expire;
            $have->save();
        }
    }

    /**
     * 课程是否属于用户购买的班级课
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2020-05-20
     *
     * @param $course_id [description]
     * @param $user_id   [description]
     */
    public function courseBelongsUserClasses($course_id, $user_id): int
    {
        $user_id = $user_id ?: request()->mid;
        $exist   = $this->alias('stu')->join('course_classes_link link', 'link.classes_id=stu.course_id')->where('stu.user_id', $user_id)->where('link.course_id', $course_id)->findOrEmpty();

        return $exist->isEmpty() ? 0 : intval($exist->classes_id);
    }

    /**
     * 课程是否属于班级课
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2020-05-20
     *
     * @param  [type] $course_id [description]
     */
    public function courseBelongsClasses($course_id): int
    {
        $exist = $this->alias('stu')->join('course_classes_link link', 'link.classes_id=stu.course_id')
            ->where('link.course_id', $course_id)->findOrEmpty();

        return $exist->isEmpty() ? 0 : intval($exist->classes_id);
    }
}
